package com.powerunion.datacollection.persistence.db.jdbc.operator;

import java.sql.SQLException;
import java.util.*;

import org.apache.log4j.Logger;

import com.powerunion.datacollection.common.AppRuntimeException;
import com.powerunion.datacollection.persistence.db.jdbc.base.AccessMannerFactory;
import com.powerunion.datacollection.persistence.db.jdbc.base.DBAccess;
import com.powerunion.datacollection.persistence.db.jdbc.base.DBAccessException;
import com.powerunion.datacollection.persistence.db.jdbc.base.ResultSetHandler;
import com.powerunion.datacollection.util.DBUtil;
import com.powerunion.util.log.LogHelper;


/**
 * 查询操作类
 * @author qyw
 *
 */
public final class QueryOperator
    extends BaseOperator {
  public QueryOperator() {
	  this.dbUtil = new DBUtil();
  }

  private static Logger logger = LogHelper.getInstance().getLogger(QueryOperator.class);
  private List SQLResultSet = null;
  private ResultSetHandler handlerImp = null;
  private DBUtil dbUtil = null;
  protected void accessImp() throws DBOperatorException {
    doAccess();
  }

  private void doAccess() throws DBOperatorException {
    try {
      handlerImp = new ResultSetHandler();
      if (!this.getParameters().isEmpty()) {
        if (!this.isUseOnlyConnectionFlag()) {
          DBAccess.query(AccessMannerFactory.getAccessManner(this.getSql(),
              this.getParameters()), handlerImp,
                         this.dbUtil.getConnection());
        }
        else {
          if (!this.isPresentConnectionUsable()) {
            this.setPresentConnection(this.dbUtil.getConnection());
          }
          DBAccess.queryForOneConnection(AccessMannerFactory.getAccessManner(this.
              getSql(), this.getParameters()), handlerImp,
                                         this.getPresentConnection());
        }
      }
      else {
        if (!this.isUseOnlyConnectionFlag()) {
          DBAccess.query(AccessMannerFactory.getAccessManner(this.getSql()),
                         handlerImp,
                         this.dbUtil.getConnection());
        }
        else {
          if (!this.isPresentConnectionUsable()) {
            this.setPresentConnection(this.dbUtil.getConnection());
          }
          DBAccess.queryForOneConnection(AccessMannerFactory.getAccessManner(this.
              getSql()), handlerImp, this.getPresentConnection());
        }
      }
      this.SQLResultSet = handlerImp.getResultDataSet();
      if (logger.isDebugEnabled()) {
        logger.debug("记录数为:" + handlerImp.getRowCount());
      }
    }
    catch (SQLException ce) {
      logger.error("数据库连接错误", ce);
      throw new DBOperatorException("数据库连接错误", ce);
    }
    catch (DBAccessException dbe) {
      logger.error("QueryOperator执行查询出错", dbe);
      throw new DBOperatorException("QueryOperator执行查询出错", dbe);
    }
  }

  /**
   * 查询返回的结果集是否可用
   * true--结果可用，拥有记录
   * false--结果不可用，没有记录集
   *
   * @return boolean
   */
  public boolean resultSetAvailable() {
    ResultSetHandler imp = getRsHandler();
    if (imp.getRowCount() > 0) {
      return true;
    }
    else {
      return false;
    }
  }

  ResultSetHandler getRsHandler() {
    if (handlerImp == null) {
      throw new AppRuntimeException("数据还没完成访问（access）操作"); 
    }
    return handlerImp;
  }

  /**
   * 返回sql语句返回的结果列表
   *
   * @return List
   * @throws DBOperatorException
   */
  public List getSqlResultSet() {
    if (!this.isAccessed()) {
      throw new AppRuntimeException("数据还没完成访问（access）操作");
    }
    return SQLResultSet;
  }
  
}
